package com.sftz.modules.minapp.personal.service;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.nutz.dao.Dao;
import org.nutz.dao.SqlManager;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.Param;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sftz.assets.entities.InstitutionStudentFormStatusEntity;
import com.sftz.assets.entities.InstitutionStudentFormValueEntity;
import com.sftz.framework.rersult.MobileResult;
import com.sftz.framework.util.IdCardUtil;
import com.sftz.framework.util.ValidateUtil;
import com.sftz.modules.minapp.personal.dto.StudentFormValueDto;
import com.sftz.modules.minapp.personal.enums.InstitutionFormDataTypeEnum;
import com.sftz.modules.minapp.personal.enums.InstitutionFormRequireEnum;
import com.sftz.modules.minapp.personal.form.StudentInstForm;
import com.uxuexi.core.common.util.DateTimeUtil;
import com.uxuexi.core.common.util.EnumUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;

@IocBean
public class StudentFormViewService {

	private static final Log log = Logs.get();

	@Inject
	private StudentFormService studentFormService;

	/**
	 * 注入容器中的dbDao对象，用于数据库查询、持久操作 
	 */
	@Inject
	private IDbDao dbDao;

	/**nutz dao*/
	@Inject
	private Dao nutDao;

	/**
	 * 注入容器中的sqlManager对象，用于获取sql
	 */
	@Inject
	private SqlManager sqlManager;

	/**
	 * 查询机构表单项
	 */
	public Map<String, Object> queryItems(@Param("..") StudentInstForm form) {
		Map<String, Object> map = Maps.newHashMap();
		Integer institutionId = form.getInstitutionId();
		if (Util.isEmpty(institutionId) || institutionId <= 0) {
			Integer courseId = form.getCourseId();
			institutionId = studentFormService.queryInstitutionId(courseId);
		}
		List<StudentFormValueDto> itemList = studentFormService.queryFormItems(institutionId);
		map.put("itemList", itemList);
		map.put("courseId", form.getCourseId());
		return map;
	}

	@Aop("txDb")
	public Map<String, Object> saveOrUpdate(@Param("content") final String content, final HttpSession session) {
		List<StudentFormValueDto> items = null;
		try {
			items = Json.fromJsonAsList(StudentFormValueDto.class, content);
		} catch (Exception e) {
			return MobileResult.error("提交数据错误", null);
		}
		if (!Util.isEmpty(items)) {
			for (StudentFormValueDto item : items) {
				String itemName = item.getItemName();
				String itemValue = item.getItemValue();
				if (Util.isEmpty(itemValue) && InstitutionFormRequireEnum.REQUIRED.intKey() == item.getNecessary()) {
					return MobileResult.error(itemName + "不能为空", null);
				} else {
					Integer dataType = item.getDataType();
					int minLength = (null == item.getMinLength()) ? 0 : item.getMinLength();
					int maxLength = (null == item.getMaxLength()) ? 0 : item.getMaxLength();

					InstitutionFormDataTypeEnum dte = EnumUtil.get(InstitutionFormDataTypeEnum.class, dataType);
					switch (dte) {
					case ID_CARD:
						if (!IdCardUtil.checkIdNumberRegex(itemValue)) {
							return MobileResult.error("身份证格式不正确", null);
						}
						//下一个
						continue;
					case TEL:
						if (!ValidateUtil.validateTel(itemValue)) {
							return MobileResult.error("手机号格式不正确", null);
						}
						continue;
					case NUM:
						if (!ValidateUtil.validateNumber(itemValue, minLength, maxLength)) {
							return MobileResult.error(itemName + ":请输入长度在" + minLength + "到" + maxLength + "之间的数字",
									null);
						}
						continue;
					case TEXT:
						if (!ValidateUtil.validateText(itemValue, minLength, maxLength)) {
							return MobileResult.error(itemName + ":请输入长度在" + minLength + "到" + maxLength + "之间的字符",
									null);
						}
						continue;
					default:
						return MobileResult.error("表单数据类型不正确,dataType:" + dataType, null);
					}
				}
			}

			/*LoginQueryCollegeDto user = (LoginQueryCollegeDto) session
					.getAttribute(UserPhoneloginViewService.USERLOGINWEBUSER);
			Integer userId = user.getId();*/
			Integer userId = 78;
			List<InstitutionStudentFormValueEntity> toBeSave = Lists.transform(items,
					new Function<StudentFormValueDto, InstitutionStudentFormValueEntity>() {
						@Override
						public InstitutionStudentFormValueEntity apply(StudentFormValueDto from) {
							InstitutionStudentFormValueEntity to = new InstitutionStudentFormValueEntity();
							to.setItemId(from.getItemId());
							to.setItemValue(from.getItemValue());
							to.setUserId(userId);
							to.setCreateTime(DateTimeUtil.nowDateTime());
							return to;
						}
					});

			studentFormService.saveOrUpdate(toBeSave);

			//如果是第一次保存机构表单
			Integer institutionId = items.get(0).getInstitutionId();
			if (!studentFormService.isFilled(userId, institutionId)) {
				InstitutionStudentFormStatusEntity stat = new InstitutionStudentFormStatusEntity();
				stat.setInstitutionId(institutionId);
				stat.setUserId(userId);
				dbDao.insert(stat);
			}
			return MobileResult.success("SUCCESS", null);
		}
		return MobileResult.error("提交数据错误", null);
	}
}
